package day3;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
// HTTP 服务端
public class HTTPServer {
    public static void main(String[] args) throws IOException {
        // 我们使用短连接
        ServerSocket serverSocket = new ServerSocket(80);
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                // 不管对方发给我们的 请求 是什么，一律使用统一的响应回复对方
                OutputStream os = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
                String html = "<a href='https://www.baidu.com/'>百度一下</a>";   // 我们的响应体
                byte[] bytes = html.getBytes("UTF-8");
                int contentLength = bytes.length;
                String response = "HTTP/1.0 200 OK\r\n" +
                        "Content-Type: application/octet-stream; charset=utf-8\r\n" +
                        "Content-Length: 49\r\n" +
                        "\r\n" +
                        html;

                writer.print(response);
                writer.flush();

                socket.close();
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }
    }
}
